import { Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { StatusFollowService } from '@core/statusFollow.service';
import { LocalStorage } from '@core/local.storage';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ReuseTabService } from '@delon/abc';
import { ExportFileService } from '@core/exportFile';

@Component({
  selector: 'app-zdrwgzqd.component',
  templateUrl: './zdrwgzqd.component.html',
  styleUrls: ['./zdrwgzqd.component.less']
})

export class ZdrwgzqdComponent implements OnInit {
  userInfo = JSON.parse(this.ls.get('loginInfo'));
  queryParam: any = {};
  tableData = []
  pageType: any;
  pageSize = '20';
  pageTotal = 0;
  pageIndex = 1;
  statusList = ['未完成', '完成'];
  detailParams: any;
  loading = false;
  editor: any = {};
  jindu: any = {};
  wcqk: any = {};
  phbmNodes = [];
  qtbmNodes = [];
  gzxmList: any = [];
  lockHeadScroll = { x: '3000px', y: `${window.innerHeight - 290}px` };
  mode: any;

  constructor(
    private http: _HttpClient,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    public statusFollowService: StatusFollowService,
    private reuseTabService: ReuseTabService,
    public message: NzMessageService,
    private ls: LocalStorage,
    private exportFile: ExportFileService,
    private modalService: NzModalService,
  ) { }

  ngOnInit(): void {
    const title = {
      edit: '工作任务清单',
      query: '任务清单查询'
    }

    this.activatedRoute.params.subscribe(params => {
      this.mode = params.mode; // edit query
      this.reuseTabService.title = title[params.mode] || '任务清单';
    });
    this.initYear();
    this.initEditor();
    this.initJindu();
    this.initWcqk();
    this.getPhbm();
    this.getQtbm();
    this.getGzxmList();
    this.query(true);
  }
  initYear() {
    this.queryParam._year = new Date();
  }
  initEditor() {
    this.editor = {
      visible: false,
      title: '',
      width: '650px',
      params: {},
      cancel: () => {
        this.editor.visible = false;
      },
    }
  }
  initJindu() {
    this.jindu = {
      sizeStatus: 'normal',
      visible: false,
      title: '',
      width: '650px',
      params: {},
      btnClick: (v) => {
        this.jindu.sizeStatus = v;
        if (v === 'max') {
          this.jindu.width = '100vw';
        } else {
          this.jindu.width = '650px';
        }
      },
      cancel: () => {
        this.jindu.visible = false;
      },
    }
  }
  initWcqk() {
    this.wcqk = {
      sizeStatus: 'normal',
      visible: false,
      title: '',
      width: '1400px',
      params: {},
      btnClick: (v) => {
        this.wcqk.sizeStatus = v;
        if (v === 'max') {
          this.wcqk.width = '100vw';
        } else {
          this.wcqk.width = '1400px';
        }
      },
      cancel: () => {
        this.wcqk.visible = false;
      },
    }
  }
  getPhbm() {
    const dataurl = environment.apiBase + '/csmis/getPublicOrgTree.jwt?view=all';
    this.http.get(dataurl).subscribe(res => {
      res.unshift({ title: "各车间分会", isLeaf: true, key: "gcjfh" });
      res.unshift({ title: "各团支部", isLeaf: true, key: "gtzb" });
      res.unshift({ title: "各党支部(总支)", isLeaf: true, key: "gdzbzz" });
      this.phbmNodes = res;
    });
  }
  getQtbm() {
    let dataurl = environment.apiBase + '/csmis/getKmnOrgTree.jwt';
    switch (this.mode) {
      case 'duanquery':
        dataurl += '?onlyShowSeg=1';
        break;
      case 'chejianquery':
        dataurl += '?showSeg=0&showAll=1';
        break;
    }
    this.http.get(dataurl).subscribe(res => {
      this.qtbmNodes = res;
    });
  }
  getGzxmList() {
    this.getGzxm().subscribe(res => {
      this.gzxmList = res.data;
    })
  }

  getOrderGroup(data, keyName) {
    const dataGroup = new Map();
    const tempGroup = {};
    const orderP = new Set();
    data.forEach(row => {
      const key = row[keyName];
      orderP.add(key);
      if (tempGroup[key]) {
        tempGroup[key].push(row)
      } else {
        tempGroup[key] = [row];
      }
    });
    orderP.forEach((id: string) => {
      dataGroup.set(id, tempGroup[id])
    });
    return dataGroup;
  }

  formatQueryRes(_data) {
    const data = [..._data];
    const orderGroup = this.getOrderGroup(data, 'projectId');
    orderGroup.forEach((group, groupName) => {
      const entryPointGroup = this.getOrderGroup(group, 'entryPoint');
      orderGroup.set(groupName, entryPointGroup);
    });

    const tableData = [];
    orderGroup.forEach((group, groupName) => {
      let groupLen = 0;
      const groupData = []
      group.forEach((_group: any, _groupName) => {
        // _group[0]._rowspanXM = group.length;
        _group[0]._rowspanXD = _group.length;
        groupLen += _group.length
        groupData.push(..._group);
      });
      groupData[0]._rowspanXM = groupLen;
      tableData.push(...groupData);
    }); 
    return tableData;
  }

  formatHref(data) {
    return environment.apiBase + '/csmis' + data.fileUrl;
  }

  query(fromBeginning = false) {
    const param: any = {
      page: fromBeginning === false ? this.pageIndex : 1,
      limit: this.pageSize,
    };
    if (this.mode === 'edit') {
      param.leadPartId = this.userInfo.VC_ORG$ID;
    }
    if (this.queryParam._year) {
      this.queryParam.year = this.queryParam._year.getFullYear();
    } else {
      this.queryParam.year = '';
    }
    switch (this.mode) {
      case 'duanquery':
        param.queryType = 'seg';
        break;
      case 'chejianquery':
        param.queryType = 'ws';
        break;
    }
    Object.assign(param, this.queryParam);
    if (param._year) {
      delete param._year;
    }
    this.removeUselessFields(param);
    this.query_table(param).subscribe(res => {
      this.tableData = this.formatQueryRes(res.data);
      this.pageTotal = res.count;
    })

    // this.test();
  }

  checkAll(v) {
    this.tableData.forEach(row => {
      row.checked = v;
    });
  }


  statusFollow(data) {
    return this.statusFollowService.init('sxdaqkk', data);
  }

  getChecked() {
    return this.tableData.filter(row => row.checked === true);
  }

  reset() {
    this.queryParam = {};
  }

  /**
   * 删除私立字段
   * @param param  1
   */
  removePrivateFields(param) {
    Object.keys(param).forEach(key => {
      if (!(key.indexOf('_'))) {
        delete param[key];
      }
    });
  }

  /**
   * 删除null字段
   * @param param 1
   */
  removeUselessFields(param) {
    Object.keys(param).forEach(key => {
      if (!param[key]) {
        delete param[key];
      }
    });
  }



  formatDate(param) {
    if (param._begindate) {
      param.begindate = this.datePipe.transform(param._begindate, 'yyyy-MM-dd');
    }
    if (param._enddate) {
      param.enddate = this.datePipe.transform(param._enddate, 'yyyy-MM-dd');
    }
  }

  showEditor(type) {
    if (type === 'edit') {
      const checked = this.getChecked();
      if (!checked.length) {
        this.message.warning('请选择一条记录进行操作');
        return;
      }
      this.editor.title = '修改';
      this.editor.params = {
        mode: type,
        gzxmList: this.gzxmList,
        phbmNodes: this.phbmNodes,
        qtbmNodes: this.qtbmNodes,
        row: checked[0]
      }
    } else {
      this.editor.title = '新增';
      this.editor.params = {
        mode: type,
        gzxmList: this.gzxmList,
        phbmNodes: this.phbmNodes,
      }
    }

    this.editor.visible = true;

  }
  showJindu() {
    const checked = this.getChecked();
    if (!checked.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    this.jindu.visible = true;
    this.jindu.title = '填写进度';
    this.jindu.params = {
      pId: checked[0].id,
    }
  }
  showWcqk() {
    const checked = this.getChecked();
    if (!checked.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    this.wcqk.visible = true;
    this.wcqk.title = '完成情况';

    let newmode = this.mode;
    if (newmode === 'duanquery' || newmode === 'chejianquery') {
      newmode = 'query';
    }
    this.wcqk.params = {
      pId: checked[0].id,
      mode: newmode,
      // sizeMode: this.wcqk.sizeStatus
    }
  }

  deleteAll() {
    const checked = this.getChecked();
    if (!checked.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    this.modalService.confirm({
      nzTitle: `<i>确认删除</i>`,
      nzWidth: '600',
      nzContent: '确认删除吗?',
      nzOnOk: () => {
        const ids = [];
        checked.forEach(row => {
          ids.push(row.id);
        });
        this.delete(ids).subscribe(res => {
          if (res.msg === 'Ok') {
            this.message.success('删除成功');
            this.query();
          } else {
            this.message.warning('删除失败');
          }
        })
      }
    })


  }

  finish() {
    const checked = this.getChecked();
    if (!checked.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    this.modalService.confirm({
      nzTitle: `<i>确认完成</i>`,
      nzWidth: '600',
      nzContent: '确认完成吗?',
      nzOnOk: () => {
        const ids = [];
        checked.forEach(row => {
          ids.push(row.id);
        });
        this.finishBatch(ids).subscribe(res => {
          if (res.msg === 'Ok') {
            this.message.success('完成成功');
            this.query();
          } else {
            this.message.warning('完成失败');
          }
        })
      }
    })
  }
  trClick(row) {
    this.checkAll(false);
    row.checked = true;
  }

  trDbclick(row) {
    if (this.mode === 'edit') {
      this.jindu.visible = true;
      this.jindu.title = '填写进度';
      this.jindu.params = {
        pId: row.id,
      }
    }
  }

  downloadFile(row) {
    this.exportFile.getDown(environment.problem + '/keyTaskProgress/download?fileUrl=' + row.fileUrl + '&fileName=' + row.fileName, row.fileName);
  }

  dataExport() {
    let param = '';
    this.queryParam.year = this.queryParam._year ? this.queryParam._year.getFullYear() : '';
    param += '?year=' + this.queryParam.year;

    if (this.queryParam.assistPartId) {
      param += '&assistPartId=' + this.queryParam.assistPartId;
    }
    if (this.queryParam.entryPoint) {
      param += '&entryPoint=' + this.queryParam.entryPoint;
    }
    if (this.mode === 'edit') {
      param += '&leadPartId=' + this.userInfo.VC_ORG$ID;
    } else {
      if (this.queryParam.leadPartId) {
        param += '&leadPartId=' + this.queryParam.leadPartId;
      }
    }
    if (this.queryParam.projectId) {
      param += '&projectId=' + this.queryParam.projectId;
    }
    if (this.queryParam.status) {
      param += '&status=' + this.queryParam.status;
    }
    this.exportFile.getDown(environment.problem + '/keyTask/dataExcel' + param, '任务清单' + this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss'));
  }


  /**
   * 车间表查询
   * @param page  string 页码
   * @param limit  string 每页显示数量
   * @param year  string 年度
   * @param uWorkshop  string 车间编号
   * @param startdate  string 筛选-开始日期yyyy-MM-dd
   * @param enddate  string 筛选-截止日期yyyy-MM-dd
   * @param uStatus  string 筛选-0未盯控、1正在盯控、2已经完成
   */
  query_table(param) {
    const dataurl = environment.problem + '/keyTask/query';
    return this.http.get(dataurl, param);
  }
  /**
   * 
   * @param view all 配合部门，去掉就是牵头部门
   */
  // getBm(param) {
  //   const dataurl = environment.apiBase + '/csmis/getPublicOrgTree.jwt';
  //   return this.http.get(dataurl, param);
  // }

  /**
   * 工作项目
   */
  getGzxm() {
    const dataurl = environment.apiBase + '/csmis/sysdict/getSysdictsByClass.jwt?dictClass=KEYTASK_PROJECT';
    return this.http.get(dataurl);
  }

  /**
   * 删除
   * @param ids 从表主键集合
   */
  delete(ids) {
    const dataurl = environment.problem + '/keyTask/deleteBatch';
    return this.http.post(dataurl, { ids });
  }
  /**
   * 完成
   * @param ids 主键集合
   */
  finishBatch(ids) {
    const dataurl = environment.problem + '/keyTask/finishBatch';
    return this.http.post(dataurl, { ids });
  }

}
